package com.qiu.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiu.demo.entity.User;
import com.qiu.demo.entity.dto.LoginDto;
import com.qiu.demo.enums.HttpCodeEnum;
import com.qiu.demo.service.UserService;
import com.qiu.demo.util.CaptchaUtils;
import com.qiu.demo.util.JsonResult;
import com.qiu.demo.util.TokenUtil;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class ApiController {

    private final String URL = "http://localhost:8080/";

    @Value("${file.path}")
    private String filePath;

    @Resource
    private CaptchaUtils captchaUtils;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private UserService userService;

    @GetMapping("/getCode")
    public void generateCaptcha(HttpServletResponse response, String key) throws IOException {
        // 生成一个唯一的Key（可以使用UUID或用户Session ID）
        String captchaKey = "captcha:" + key;

        // 生成验证码图片并写入响应流F
        captchaUtils.generateCaptcha(captchaKey, response);
    }

    /*
     * 文件上传
     */
    @PostMapping("/updateFile")
    public JsonResult singleImage(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws FileNotFoundException { // 参数名需与前端文件标签名一样
        // 获取项目classes/static的地址
        String path = filePath;
        // String fileName = file.getOriginalFilename(); // 获取文件名
        String fileOrigrec = file.getOriginalFilename();
        String ext = fileOrigrec.substring(fileOrigrec.lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString() + ext; // 获取文件名
        // 图片访问URI(即除了协议、地址和端口号的URL)
        String url_path = "image" + File.separator + fileName;
        String savePath = path + File.separator + url_path; // 图片保存路径
        System.out.println(savePath);
        File saveFile = new File(savePath);

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        try {
            file.transferTo(saveFile); // 将临时存储的文件移动到真实存储路径下
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回图片访问地址
        return JsonResult.success().data("filePath", URL + url_path);
    }

    /*
     * 用户登录
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody LoginDto loginDto) {
        // 验证验证码
        if (!captchaUtils.validateCaptcha(loginDto.getCaptchaKey(), loginDto.getCaptcha())) {
            return JsonResult.error().codeAndMessage(HttpCodeEnum.RC300); // 验证码错误
        }
        captchaUtils.clearCaptcha(loginDto.getCaptchaKey());

        User user = userService.getOne(
                new LambdaQueryWrapper<User>().eq(User::getUsername, loginDto.getUsername()).eq(User::getPassword,
                        loginDto.getPassword()),
                false);
        if (user == null) {
            return JsonResult.error().codeAndMessage(HttpCodeEnum.RC107);
        }
        String token = tokenUtil.getToken(user.getUserId().toString());
        return JsonResult.success().codeAndMessage(200, "登录成功").data("token", token);
    }

    /*
     * 用户注册
     */
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody LoginDto loginDto) {

        // 验证验证码
        if (!captchaUtils.validateCaptcha(loginDto.getCaptchaKey(), loginDto.getCaptcha())) {
            return JsonResult.error().codeAndMessage(HttpCodeEnum.RC300); // 验证码错误
        }
        captchaUtils.clearCaptcha(loginDto.getCaptchaKey());

        User user = userService.getOne(
                new LambdaQueryWrapper<User>().eq(User::getUsername, loginDto.getUsername()),
                false);
        if (user != null) {
            return JsonResult.error().codeAndMessage(HttpCodeEnum.RC110);
        }
        user = new User();
        user.setGender(0);
        user.setUsername(loginDto.getUsername());
        user.setNickname("user" + loginDto.getCaptchaKey());
        user.setPassword(loginDto.getPassword());
        user.setRegisterTime(LocalDateTimeUtil.now());
        user.setEmail("user" + loginDto.getCaptchaKey() + "@qq.com");
        userService.save(user);
        return JsonResult.success().codeAndMessage(200, "注册成功");
    }

}
